<template>
    <div class="container">
        <Breadcrumb :items="['menu.list', '使用记录']" />
        <a-card class="general-card" title="使用记录">
            <a-row>
                <a-col>
                    <a-form :model="formData" label-align="auto" auto-label-width>
                        <a-row :gutter="16">
                            <a-col :span="12">
                                <div class="form-item">
                                    <div class="label">{{ totalamount.totalCount ? totalamount.totalCount : 0 }}</div>
                                    <div class="content">充值订单总计(笔)</div>
                                </div>
                            </a-col>
                            <a-col :span="12">
                                <div class="form-item">
                                    <div class="label">￥{{ totalamount.totalFee ? totalamount.totalFee : 0 }}</div>
                                    <div class="content">充值金额总计(元)</div>
                                </div>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item label="订单号">
                                    <a-input allow-clear v-model="formData.businessOrderNo" placeholder="请输入" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item label="学生姓名">
                                    <a-input allow-clear v-model="formData.username" placeholder="请输入" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item label="学生学号">
                                    <a-input allow-clear v-model="formData.userAccount" placeholder="请输入" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item label="生产厂家">
                                    <a-input allow-clear v-model="formData.manufacturer" placeholder="请输入" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item label="终端编号">
                                    <a-input allow-clear v-model="formData.imei" placeholder="请输入" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="8">
                                <a-form-item label="时间">
                                    <a-range-picker showTime :time-picker-props="{
                                        defaultValue: ['00:00:00', '00:00:00']
                                    }" v-model="rangeValue" @change="onChange" @select="onSelect" style=" width: 100%; " />
                                </a-form-item>
                            </a-col>
                            <a-col :span="10">
                                <div class="search-btn">
                                    <a-button type="primary" @click="onPageChange(1)">查询</a-button>
                                    <a-button type="primary" status="success"
                                        @click="getRecordsExport(formData)">导出</a-button>
                                </div>
                            </a-col>
                        </a-row>
                    </a-form>
                </a-col>
            </a-row>
        </a-card>

        <div class="container-table">
            <a-card class="general-card">
                <!-- :scroll="{ x: 270 }" -->
                <a-table :virtual-list-props="{ height: 460 }" :scroll="{ x: '120%', y: '100%' }" :loading="loadingEdit"
                    :columns="columns" :data="tableList" :pagination="pagination" @page-change="onPageChange">
                    <template #orderStatus="{ record }">
                        <a-tag v-if="record.orderStatus == 'CREATED'" color="blue">
                            已创建
                        </a-tag>
                        <a-tag v-if="record.orderStatus == 'PAID'" color="green">
                            已支付
                        </a-tag>
                        <a-tag v-if="record.orderStatus == 'CANCELLED'" color="gray">
                            已退款
                        </a-tag>
                    </template>
                    <template #operations="{ record }">
                        <a-popconfirm content="确认是否退款?" type="warning" @ok="getpaymentbyBusinessOrderNo(record)">
                            <a-button type="text" size="small" v-if="record.orderStatus == 'PAID'">
                                退款
                            </a-button>
                        </a-popconfirm>



                    </template>
                </a-table>
            </a-card>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue';

import { baseUrl } from "@/api/interceptor"


import { endbackfindAll, recordsstats, recordsexport, paymentbyBusinessOrderNo } from '@/api/hairdryer'

import moment from 'moment';



let loadingEdit = ref(false);
//查询列表
let formData = ref({
    page: 1,
    size: 10,
    borrowTimeStart: (moment().startOf('month').format('YYYY-MM-DD')) + "T00:00:00",
    borrowTimeEnd: (moment().endOf('month').format('YYYY-MM-DD')) + "T00:00:00"
})
const pagination = ref({
    current: formData.value.page,
    pageSize: formData.value.size,
    showTotal: true,
    total: 0
}); // 分页属性
const columns = ref([
    {
        title: '订单号',
        width: '190',
        dataIndex: 'businessOrderNo',
    },
    {
        title: '学生姓名',
        width: '180',
        dataIndex: 'username',
    },
    {
        title: '学号',
        width: '180',
        dataIndex: 'userAccount',
    },
    {
        title: '金额',
        width: '90',
        dataIndex: 'fee',
    },
    {
        title: '终端编号',
        width: '160',
        dataIndex: 'imei',
    },
    {
        title: '生产厂家',
        width: '120',
        dataIndex: 'manufacturer',
    },
    {
        title: '使用时间(分钟)',
        width: '150',
        dataIndex: 'minutes',
    },
    {
        title: '开始时间',
        width: '180',
        dataIndex: 'usageRecordcreatedAt',
    },
    {
        title: '结束时间',
        width: '180',
        dataIndex: 'returnTime',
    },
    {
        title: '网点名称',
        width: '180',
        dataIndex: 'name',
    },
    {
        title: '地址',
        width: '180',
        dataIndex: 'location',
    },
    {
        title: '状态',
        width: '150',
        dataIndex: 'orderStatus',
        slotName: 'orderStatus',
    },
    {
        title: '操作',
        width: '100',
        align: 'center',
        fixed: 'right',
        dataIndex: 'operations',
        slotName: 'operations',
    },

])

//时间选择器
let rangeValue = ref([moment().startOf('month').valueOf(), moment().endOf('month').valueOf()])
const onSelect = (dateString, date) => {
    console.log('onSelect: ', dateString, date);

    // formData.value.borrowTimeStart = '';
    // formData.value.borrowTimeEnd = '';

    // amountForm.value.start = '';
    // amountForm.value.end = '';
}
const onChange = (dateString, date) => {
    console.log('onChange: ', dateString, date);

    if (dateString) {
        // let one = dateString[0].split(" ")[0]
        let one =  dateString[0]
        let two =  dateString[1]
        
        formData.value.borrowTimeStart = one.split(" ")[0] + "T"+ one.split(" ")[1];
        formData.value.borrowTimeEnd =two.split(" ")[0] + "T"+ two.split(" ")[1];

        amountForm.value.start = one.split(" ")[0];
        amountForm.value.end = two.split(" ")[0];
    } else {
        formData.value.borrowTimeStart = '';
        formData.value.borrowTimeEnd = '';

        amountForm.value.start = '';
        amountForm.value.end = '';
    }


}

const tableList = ref([]);

const onPageChange = (current) => {
    formData.value.page = current;
    pagination.value.current = current;
    getendbackfindAll()
    getrecordsstats()
};


let getendbackfindAll = async () => {
    loadingEdit.value = true;

    try {
         tableList.value = []
        let res = await endbackfindAll(formData.value)
        console.log(res, 'dddd');


        // tableList.value = res.data.content 

        tableList.value = [
            ...tableList.value,
            ...res.data.content.map(({ usageRecord, device }) => ({
                usageRecordcreatedAt:usageRecord.createdAt,
                ...usageRecord,
                ...device,
            })),
        ];


        pagination.value.total = res.data.totalElements;
        loadingEdit.value = false;


    } catch (err) {
        loadingEdit.value = false;

    }
}

//获取总金额
let totalamount = ref({})
let amountForm = ref({
    start: moment().startOf('month').format('YYYY-MM-DD'),
    end: moment().endOf('month').format('YYYY-MM-DD')
})
const getrecordsstats = async () => {
    try {
        let res = await recordsstats(amountForm.value)
        console.log(res);
        totalamount.value = res.data


    } catch (error) {

    }
}


//退款
const getpaymentbyBusinessOrderNo = async (data) => {
    try {
        loadingEdit.value = true;

        let res = await paymentbyBusinessOrderNo({ businessOrderNo: data.businessOrderNo })
        Message.success('退款成功');

        getendbackfindAll()
        getrecordsstats()

    } catch (error) {
        loadingEdit.value = false;
        console.log(error);

    }
}


//导出
const getRecordsExport = (formData) => {
    // 3. 合并参数（手动过滤掉 null/undefined）
    const params = {};
    Object.keys(formData).forEach((key) => {
        if (formData[key] != null) { // 跳过 null 和 undefined
            params[key] = formData[key];
        }
    });

    // 4. 使用 URLSearchParams 序列化
    const searchParams = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
        searchParams.append(key, value);
    });

    // 5. 拼接 URL 并打开新窗口
    window.open(`${baseUrl}/blow/usage-records/export?${searchParams.toString()}`, '_blank');


};


onMounted(() => {
    getendbackfindAll()
    getrecordsstats()
})

</script>
<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;

    .search-btn {
        width: 100%;
        display: flex;
        justify-content: flex-end;
        gap: 0 10px;
    }


    .container-table {
        margin-top: 20px;

        .general-card {
            box-sizing: border-box;
            padding: 20px 0;


        }
    }
}

.form-item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 16px;

    .label {
        font-size: 18px;
        font-weight: bold;
    }

    .content {
        font-size: 16px;

    }
}
</style>